<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="公司名称" prop="companyName">
        <el-input
          v-model="queryParams.companyName"
          placeholder="请输入公司名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="承运商编码" prop="carrierCode">
        <el-input
          v-model="queryParams.carrierCode"
          placeholder="请输入承运商编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="承运商类型" prop="carrierType">
        <el-input
          v-model="queryParams.carrierType"
          placeholder="请输入承运商类型"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="dateRange">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除
        </el-button>
      </el-col>

      <!-- 新增导入按钮 -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-upload2" size="mini" @click="handleImport">导入</el-button>
      </el-col>
      <!-- 新增导出按钮 -->
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="carrierList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="公司名称" align="center" prop="companyName"/>
      <el-table-column label="承运商编码" align="center" prop="carrierCode"/>
      <el-table-column label="承运商类型" align="center" prop="carrierType"/>
      <el-table-column label="司机数量" align="center" prop="driverCount">
        <template slot-scope="scope">
          <!-- 悬停提示组件 -->
          <el-tooltip
            placement="top"
            effect="dark"
            :disabled="scope.row.driverCount === 0"
          >
            <!-- 提示框内容（动态加载司机信息） -->
            <div slot="content">
              <div class="open-driver">此处只显示启用司机</div>
              <div v-if="driverMessage.length>0">
                <div v-for="(driver, idx) in driverMessage" :key="idx" style="padding: 3px 0;">
                  {{ idx + 1 }}. {{ driver.name }}（电话：{{ driver.phoneNumber }}，证件类型：{{ driver.licenseType }}）
                </div>
              </div>
              <div v-else>无司机信息</div>
            </div>
            <!-- 触发提示的元素（司机数量） -->
            <span @mouseenter="loadDrivers(scope.row.carrierId)">{{ scope.row.driverCount }}</span>
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column label="车辆数量" align="center" prop="vehicleCount"/>
      <el-table-column label="公司地址" align="center" prop="companyAddress"/>
      <el-table-column label="是否签订合同" align="center" prop="isContractSigned">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isContractSigned === '0' ? 'success' : 'warning'">
            {{ contractStatusFormat(scope.row) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === '0' ? 'success' : 'warning'">
            {{ statusFormat(scope.row) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改承运商信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="公司名称" prop="companyName">
              <el-input v-model="form.companyName" placeholder="请输入公司名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="承运商编码" prop="carrierCode">
              <el-input v-model="form.carrierCode" placeholder="请输入承运商编码"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="承运商类型" prop="carrierType">
              <el-input v-model="form.carrierType" placeholder="请输入承运商类型"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="司机数量" prop="driverCount">
              <el-input-number v-model="form.driverCount" controls-position="right" :min="0"/>
            </el-form-item>

          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="车辆数量" prop="vehicleCount">
              <el-input-number v-model="form.vehicleCount" controls-position="right" :min="0"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否签订合同" prop="isContractSigned">
              <el-select v-model="form.isContractSigned" placeholder="请选择是否签订合同" style="width: 100%">
                <el-option
                  v-for="dict in contractStatusOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
                <el-option
                  v-for="dict in statusOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司地址" prop="companyAddress">
              <el-input v-model="form.companyAddress" placeholder="请输入公司地址"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listCarrier, getCarrier, addCarrier, updateCarrier, delCarrier} from "@/api/tms/base/carrier";
import {getDriversByCarrierId} from "@/api/tms/base/driver"; // 引入司机接口
import * as XLSX from 'xlsx';

export default {
  name: "Carrier",
  data() {
    return {
      driverMessage: [],
      driversMap: {},       // 存储司机信息：{ carrierId: [司机列表] }
      driverLoading: {},   // 标记加载状态：{ carrierId: true/false }
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 承运商信息表格数据
      carrierList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 合同状态数据字典
      contractStatusOptions: [
        {value: "0", label: "是"},
        {value: "1", label: "否"}
      ],
      // 状态数据字典
      statusOptions: [
        {value: "0", label: "启用"},
        {value: "1", label: "停用"}
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyName: undefined,
        carrierCode: undefined,
        carrierType: undefined,
        params: {
          beginTime: undefined,
          endTime: undefined
        }
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        companyName: [
          {required: true, message: "公司名称不能为空", trigger: "blur"}
        ],
        carrierCode: [
          {required: true, message: "承运商编码不能为空", trigger: "blur"}
        ],
        carrierType: [
          {required: true, message: "承运商类型不能为空", trigger: "blur"}
        ],
        isContractSigned: [
          {required: true, message: "是否签订合同不能为空", trigger: "change"}
        ],
        status: [
          {required: true, message: "状态不能为空", trigger: "change"}
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {

    // 加载司机信息（鼠标悬停时触发）
    loadDrivers(carrierId) {
      console.log(22222, carrierId)
      // 已加载或正在加载则跳过
      // if (this.driversMap[carrierId] || this.driverLoading[carrierId]) {
      //   return;
      // }
      // // 标记加载中
      // this.driverLoading[carrierId] = true;
      // // 调用后端接口
      getDriversByCarrierId(carrierId).then(response => {
        this.driverMessage = response.data
        console.log(111, response)
        //   this.driversMap[carrierId] = response.data; // 缓存司机数据
        // }).catch(() => {
        //   this.driversMap[carrierId] = []; // 失败时设为空数组
        // }).finally(() => {
        //   this.driverLoading[carrierId] = false; // 清除加载状态
      });
    },


    /** 查询承运商信息列表 */
    getList() {
      this.loading = true;
      this.driversMap = {};       // 清空司机缓存
      this.driverLoading = {};    // 清空加载状态
      // 处理日期范围参数
      if (this.dateRange && this.dateRange.length === 2) {
        this.queryParams.params.beginTime = this.dateRange[0];
        this.queryParams.params.endTime = this.dateRange[1];
      } else {
        this.queryParams.params.beginTime = undefined;
        this.queryParams.params.endTime = undefined;
      }

      listCarrier(this.queryParams).then(response => {
        this.carrierList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 合同状态显示转换
    contractStatusFormat(row) {
      const contractStatusMap = {
        "0": "是",
        "1": "否"
      };
      return contractStatusMap[row.isContractSigned] || "未知";
    },
    // 状态显示转换
    statusFormat(row) {
      const statusMap = {
        "0": "启用",
        "1": "停用"
      };
      return statusMap[row.status] || "未知状态";
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.carrierId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加承运商信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const carrierId = row.carrierId || this.ids;
      getCarrier(carrierId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改承运商信息";
      });
    },

    /** 导入按钮操作 */
    handleImport() {
      this.importVisible = true;
    },

    /** 导出按钮操作 */
    handleExport() {
      // 使用前端数据导出，不依赖后端接口
      this.$confirm('确定要导出承运商数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        try {
          // 准备导出的数据，只包含需要的字段
          const exportData = this.carrierList.map(row => ({
            '公司名称': row.companyName,
            '承运商编码': row.carrierCode,
            '承运商类型': row.carrierType,
            '司机数量': row.driverCount,
            '车辆数量': row.vehicleCount,
            '公司地址': row.companyAddress,
            '是否签订合同': this.contractStatusFormat(row),
            '状态': this.statusFormat(row)
          }));

          // 创建工作簿
          const ws = XLSX.utils.json_to_sheet(exportData);
          const wb = XLSX.utils.book_new();
          XLSX.utils.book_append_sheet(wb, ws, '承运商数据');

          // 导出文件
          XLSX.writeFile(wb, '承运商数据.xlsx');

          this.$modal.msgSuccess('导出成功');
        } catch (error) {
          console.error('导出失败:', error);
          this.$modal.msgError('导出失败');
        }
      }).catch(() => {
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.carrierId != null) {
            updateCarrier(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCarrier(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const carrierIds = row.carrierId || this.ids;
      this.$modal.confirm('是否确认删除承运商编号为"' + carrierIds + '"的数据项？').then(() => {
        return delCarrier(carrierIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 表单重置 */
    reset() {
      this.form = {
        carrierId: null,
        companyName: null,
        carrierCode: null,
        carrierType: null,
        driverCount: 0,
        vehicleCount: 0,
        companyAddress: null,
        isContractSigned: null,
        status: null
      };
      this.resetForm("form");
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    }
  }
};
</script>
<style scoped>
.open-driver {
  color: #1ab394;
}
</style>

